import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { LoggerService } from '@/common/logger/logger.service';
import { UploadFileInterface } from './interfaces/file.interface';
import { EnvEnum } from '../enums/env.enum';
import { handleError } from '@/utils/handle.error';
import { PrismaService } from '../prisma/prisma.service';

@Injectable()
export class UploadService {

  constructor(
    private readonly configService: ConfigService,
    private readonly logger: LoggerService,
    private readonly prismService: PrismaService,
  ) {
    this.logger.setContext(UploadService.name)
  }

  async uploadSingle(file: UploadFileInterface, id: number) {
    try {
      this.logger.log(`${this.uploadSingle.name} was called`);
      const { url, name } = await this.getFileURL(file)
      if (id) {
        const res = await this.prismService.images.create({
          data: {
            name, url, type: 'default', userId: id
          },
          select: {
            id: true
          }
        })
        console.log('打印***res', res)
      }
      return { name, url }
    } catch (error) {
      handleError(this.logger, error, {
        common: '上传文件失败'
      })
    }
  }

  async uploadMultiple(files: UploadFileInterface[]) {
    try {
      this.logger.log(`${this.uploadMultiple.name} was called`);
      return await Promise.all(files.map((file) => this.getFileURL(file)));
    } catch (error) {
      handleError(this.logger, error, {
        common: '批量上传文件失败'
      })
    }
  }


  async getFileURL(file: UploadFileInterface) {
    const dateFolder = file.destination.split("files")[1].slice(1);
    return {
      url: `${this.configService.get(
        EnvEnum.UPLOAD_ADDRESS,
      )}/static/${dateFolder}/${file.filename}`,
      name: file.originalname,
    }
  }
}
